<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Safe Car Rental</title>
  <style>
    /* 基础样式 */
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    body {
      font-family: Arial, sans-serif;
      background: #007bff;
    }
    /* 主页面内容 */
    .blue-rectangle {
      width: 95%;
      max-width: 1200px;
      margin: 40px auto;
    }
    .header {
      text-align: center;
      color: #fff;
      margin-bottom: 20px;
    }
    .contact-block {
      background: #fff;
      border-radius: 0.5rem;
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
      padding: 1rem 1.5rem;
      margin: 1.5rem auto;
      max-width: 600px;
      text-align: center;
    }
    .contact-block .contacts {
      display: flex;
      flex-direction: column;
      gap: 0.5rem;
      font-size: 1.5rem;
    }
    .contact-block .contacts i {
      margin-right: 0.5rem;
      color: #007bff;
    }

    .header h1 {
      font-size: 64px;
      font-weight: bold;
    }
    .header h3 {
      font-size: 24px;
      margin-top: 10px;
      color: #e0f0ff;
    }
    .footer {
      text-align: center;
      color: #fff;
      font-size: 14px;
      margin-top: 40px;
    }
    /* Filter 区域样式 */
    .filter-container {
      background: #fff;
      padding: 10px 20px;
      border-radius: 12px;
      margin-bottom: 20px;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      gap: 15px;
    }
    .filter-group label {
      margin-right: 5px;
      font-size: 14px;
    }
    .filter-group select {
      padding: 5px 10px;
      border-radius: 6px;
      border: 1px solid #ccc;
    }
    /* car list 样式 */
    .car-list {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
    .car {
      display: flex;
      flex-direction: row;
      background: #fff;
      border-radius: 20px;
      overflow: hidden;
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
      transition: transform 0.3s ease, box-shadow 0.3s ease;
      cursor: pointer;
      height: 200px;
    }
    .car:hover {
      transform: translateY(-5px);
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
    }
    .car-img {
      width: 60%;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #fff;
      padding: 10px;
    }
    .car-img img {
      border-radius: 12px;
      max-width: 100%;
      max-height: 100%;
      object-fit: contain;
    }
    .car-text {
      width: 40%;
      background-color: #fff;
      padding: 20px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      text-align: left;
      overflow: hidden;
      word-break: break-word;
    }
    .car-title {
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 10px;
      line-height: 1.4;
    }
    .car-details {
      font-size: 16px;
      line-height: 1.8;
      white-space: pre-line;
    }
    @media (max-width: 768px) {
      .car {
        height: auto;
      }
      .car-img, .car-text {
        width: 100%;
      }
      .car-img {
        height: 200px;
      }
    }
    /* 语言选择覆盖层 */
    #langOverlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.6);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 9999;
    }
    #langOverlay .lang-container {
      background: #fff;
      padding: 40px 50px;
      border-radius: 12px;
      text-align: center;
      box-shadow: 0 8px 20px rgba(0,0,0,0.2);
      max-width: 300px;
      width: 90%;
    }
    #langOverlay h2 {
      margin-bottom: 30px;
      font-size: 24px;
      color: #333;
    }
    #langOverlay button {
      display: inline-block;
      width: 100%;
      max-width: 200px;
      margin: 8px auto;
      padding: 12px 0;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-size: 18px;
      font-weight: bold;
      color: #fff;
      transition: background-color 0.3s, transform 0.3s;
    }
    #langOverlay button:hover {
      opacity: 0.9;
      transform: scale(1.02);
    }
  </style>
</head>
<body>
  <!-- 语言选择覆盖层：进入页面时先显示 -->
  <div id="langOverlay">
    <div class="lang-container">
      <h2 data-i18n="chooseLanguageTitle">请选择语言</h2>
      <button onclick="selectLanguage('zh')" class="lang-zh" style="background-color: #007bff;">中文</button>
      <button onclick="selectLanguage('en')" class="lang-en" style="background-color: #28a745;">English</button>
      <button onclick="selectLanguage('th')" class="lang-th" style="background-color: #ffc107;">ไทย</button>
    </div>
  </div>

  <!-- 主页面内容 -->
  <div class="blue-rectangle">
    <div class="header">
      <h1 data-i18n="companyName">安全车行</h1>
      <h3 data-i18n="subtitle">Safe Car Rental</h3>
    </div>

    <!-- 在这里插入联系方式 -->
    <div class="contact-block bg-white rounded shadow-sm py-3 mb-4 text-center">
      <p class="h5 fw-bold mb-2" data-i18n="contactTitle">联系方式</p>
      <div class="d-flex justify-content-center flex-wrap gap-4">
        <div>
          <i class="fas fa-phone-alt text-primary me-1"></i>
          <span>0954623651</span>
          <small class="text-muted">(中文 / English / ไทย)</small>
        </div>
        <div>
          <i class="fas fa-phone-alt text-success me-1"></i>
          <span>0935234324</span>
          <small class="text-muted">(ไทย / 中文)</small>
        </div>
        <div>
          <i class="fas fa-phone-alt text-warning me-1"></i>
          <span>0937851189</span>
          <small class="text-muted">(中文)</small>
        </div>
      </div>
    </div>

    <!-- Filter 区域 -->
    <div class="filter-container">
      <div class="filter-group">
        <label data-i18n="rentalTypeLabel" for="rentalType">租期：</label>
        <select id="rentalType" onchange="onRentalTypeChange()">
          <option value="day" data-i18n="dayOption">日租</option>
          <option value="week" data-i18n="weekOption">周租</option>
          <option value="month" data-i18n="monthOption">月租</option>
        </select>
      </div>
      <div class="filter-container">
        <div class="filter-group">
          <label data-i18n="priceRangeLabel" for="priceRange">价格区间：</label>
          <select id="priceRange" onchange="filterCars()">
            <!-- 动态生成 -->
          </select>
        </div>
        <div class="filter-group">
          <label data-i18n="languageLabel" for="langSelect">语言</label>
          <select id="langSelect">
            <option value="zh" data-i18n="optionZh">中文</option>
    	      <option value="en" data-i18n="optionEn">English</option>
     	      <option value="th" data-i18n="optionTh">ไทย</option>
          </select>
        </div>
      </div>
      <div class="filter-group">
        <label for="filterStart">取车日期：</label>
        <input type="date" id="filterStart" onchange="applyDateFilter()" />
      </div>
      <div class="filter-container">
        <div class="filter-group">
          <label for="filterEnd">还车日期：</label>
          <input type="date" id="filterEnd" onchange="applyDateFilter()" />
        </div>
      </div>
    </div>

    <div class="car-list" id="carList">
      <!-- 动态加载的车辆列表 -->
    </div>
  </div>

  <div class="footer">
    <p>
      <span data-i18n="contactLine">LINE / WhatsApp:</span>
      <span class="phone">+66 0937851189</span>
    </p>
    <p>
      <span data-i18n="contactEmail">邮箱: </span>
    <span class="contact-value">zfg77@qq.com</span>
    </p>
  </div>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-app.js";
    import { getFirestore, doc, onSnapshot, collection } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-firestore.js";

    // Firebase 配置（请替换为你的配置）
    const firebaseConfig = {
      apiKey: "YOUR_API_KEY",
      authDomain: "rental-7fe8c.firebaseapp.com",
      projectId: "rental-7fe8c",
      storageBucket: "rental-7fe8c.appspot.com",
      messagingSenderId: "263132536954",
      appId: "1:263132536954:web:55d988d88b1a078b4b9bc3"
    };
    const app = initializeApp(firebaseConfig);
    const db = getFirestore(app);

    let carsData = [];
    let ordersData = [];
    let currentLangData = {};

    onSnapshot(collection(db, "orders"), snap => {
      ordersData = snap.docs.map(d => ({
        id:   d.id,
        ...d.data()
      }));
      // 订单更新了，重新渲染
      renderCars();
    });

    // 2) 监听 orders
    onSnapshot(collection(db, "orders"), snap => {
      ordersData = [];
      snap.forEach(d => ordersData.push({ id: d.id, ...d.data() }));
      renderCars();  // 重新渲染一次，把新订单生效信息带上
    });

    // 价格区间配置
    const dayRanges = [
      { key: "range1", text: "0 - 2000", min: 0, max: 2000 },
      { key: "range2", text: "2000 - 3000", min: 2000, max: 3000 },
      { key: "range3", text: "3000 - 4000", min: 3000, max: 4000 },
      { key: "range4", text: "> 4000", min: 4000, max: Infinity }
    ];
    const weekRanges = [
      { key: "range1", text: "0 - 10000", min: 0, max: 10000 },
      { key: "range2", text: "10000 - 15000", min: 10000, max: 15000 },
      { key: "range3", text: "15000 - 20000", min: 15000, max: 20000 },
      { key: "range4", text: "> 20000", min: 20000, max: Infinity }
    ];
    const monthRanges = [
      { key: "range1", text: "0 - 20000", min: 0, max: 20000 },
      { key: "range2", text: "20000 - 40000", min: 20000, max: 40000 },
      { key: "range3", text: "40000 - 50000", min: 40000, max: 50000 },
      { key: "range4", text: "> 50000", min: 50000, max: Infinity }
    ];


    function applyDateFilter() {
      const startVal = document.getElementById("filterStart").value;
      const endVal   = document.getElementById("filterEnd").value;

      // 如果任意一边没选，就直接渲染所有可见车辆
      if (!startVal || !endVal) {
        renderCars(carsData);
          return;
      }

      const start = new Date(startVal);
      const end   = new Date(endVal);
      if (end <= start) {
        // 你也可以在 UI 上给个提示“结束日期要大于开始日期”
        renderCars([]);
        return;
      }

      // 过滤：只保留那些在 [start, end) 期间**没有**被预约的车辆
      const available = carsData.filter(car => {
        // 看 ordersData 里有没有与这辆车冲突的订单
        const conflict = ordersData.some(o => {
          if (o.carId !== car.id) return false;
          const oStart = new Date(o.startDate);
          const oEnd   = new Date(o.endDate);
          // 如果 预约开始 < 筛选结束 && 预约结束 > 筛选开始 ，说明有交集
          return oStart < end && oEnd > start;
        });
        return !conflict;
      });

      renderCars(available);
    }
    window.applyDateFilter = applyDateFilter;
    // ========== 多语言相关函数 ==========
    async function loadLanguage(lang) {
      try {
        const resp = await fetch(`lang/${lang}.json`);
        return await resp.json();
      } catch (err) {
        console.error("语言文件加载失败:", err);
        return {};
      }
    }
    function applyLanguage(langData) {
      document.querySelectorAll("[data-i18n]").forEach(el => {
        const key = el.getAttribute("data-i18n");
        if (langData[key]) {
          el.textContent = langData[key];
        }
      });
    }

    // 语言选择函数（挂载到 window 以便内联调用）
    window.selectLanguage = async function(lang) {
      localStorage.setItem("selectedLanguage", lang);
      document.getElementById("langOverlay").style.display = "none";
      document.getElementById("langSelect").value = lang;
      const langData = await loadLanguage(lang);
      applyLanguage(langData);
      filterCars();
    };

    // 语言下拉事件
    document.getElementById("langSelect").addEventListener("change", async () => {
      const chosenLang = document.getElementById("langSelect").value;
      localStorage.setItem("selectedLanguage", chosenLang);
      const langData = await loadLanguage(chosenLang);
      applyLanguage(langData);
      filterCars();
    });

    // 默认语言设置
    const savedLang = localStorage.getItem("selectedLanguage") || "zh";
    document.getElementById("langSelect").value = savedLang;

    // ========== Firestore 车辆监听 ==========
    onSnapshot(doc(db, "cars", "data"), (docSnap) => {
      if (docSnap.exists()) {
        carsData = docSnap.data().cars || [];
      } else {
        carsData = [];
      }
      onRentalTypeChange();
    });

    // ========== Filter 与 渲染 ==========
    window.onRentalTypeChange = onRentalTypeChange;
    window.filterCars = filterCars;

    function onRentalTypeChange() {
      const rentalType = document.getElementById("rentalType").value;
      const priceRangeSelect = document.getElementById("priceRange");
      priceRangeSelect.innerHTML = "";

      const allOption = document.createElement("option");
      allOption.value = "all";
      allOption.setAttribute("data-i18n", "all");
      allOption.textContent = "全部";
      priceRangeSelect.appendChild(allOption);

      const ranges = rentalType === "day" ? dayRanges :
                     rentalType === "week" ? weekRanges :
                     monthRanges;

      ranges.forEach(r => {
        const opt = document.createElement("option");
        opt.value = r.key;
        opt.textContent = r.text;
        priceRangeSelect.appendChild(opt);
      });

      filterCars();
    }

    function getMinMax(rentalType, rangeKey) {
      if (rangeKey === "all") return [0, Infinity];
      const ranges = rentalType === "day" ? dayRanges :
                     rentalType === "week" ? weekRanges :
                     monthRanges;
      const found = ranges.find(r => r.key === rangeKey);
      return found ? [found.min, found.max] : [0, Infinity];
    }

    function getCurrentLang() {
      return localStorage.getItem("selectedLanguage") || "zh";
    }

    // 根据车数据中的 text 字段获取当前语言文本，旧格式直接返回
    function getCarText(car) {
      const lang = getCurrentLang();
      if (!car.text) return "";
      if (typeof car.text === "string") {
        return car.text;
      }
      return car.text[lang] || "";
    }

    function getPriceByRentalType(car, rentalType) {
      const text = getCarText(car);
      // 使用中文正则匹配价格（如果需要支持其他语言，请在 admin 端统一写成中文价格部分）
      const pattern = rentalType === "day" ? /日租：(\d+)/ :
                      rentalType === "week" ? /周租：(\d+)/ :
                      /月租：(\d+)/;
      const match = text.match(pattern);
      return match ? parseInt(match[1]) : Infinity;
    }

    function filterCars() {
      const rentalType = document.getElementById("rentalType").value;
      const rangeKey = document.getElementById("priceRange").value;
      const [minPrice, maxPrice] = getMinMax(rentalType, rangeKey);
      const filtered = carsData.filter(car => {
        const price = getPriceByRentalType(car, rentalType);
        return price >= minPrice && price <= maxPrice;
      });
      renderCars(filtered);
    }

    function renderCars(filteredData = carsData) {
      const carList = document.getElementById("carList");
      carList.innerHTML = "";

      const today = new Date();
      const MS_PER_DAY = 1000*60*60*24;
      
      filteredData.forEach(car => {
        const rawText = getCarText(car);
        const lines = rawText.split("\n");
        const firstLine = lines[0] || "";
        const secondAndRest = lines.slice(1).join("\n");
        const imageUrl = (Array.isArray(car.images) && car.images.length > 0)
          ? car.images[0]
          : "https://via.placeholder.com/300";

          const activeOrder = ordersData.find(o=>{
          return o.carId===car.id
             && new Date(o.startDate) <= today
             && new Date(o.endDate)   >= today;
        });
        let countdownHtml = "";
        const lang = localStorage.getItem("selectedLanguage") || "zh";
        if(activeOrder){
          const end = new Date(activeOrder.endDate);
          const daysLeft = Math.ceil((end - today)/MS_PER_DAY);
          let text;
          if (lang === "zh") {
            text = `还车倒计时：${daysLeft} 天`;
          } else if (lang === "en") {
            text = `Return in ${daysLeft} days`;
          } else { // "th"
            text = `เหลือ ${daysLeft} วันจนถึงวันคืนรถ`;
          }
          countdownHtml = `<p style="color:#d9534f;font-weight:bold">${text}</p>`;
        }

        const carDiv = document.createElement("div");
        carDiv.classList.add("car");

        carDiv.onclick = () => {
          const carDataStr = JSON.stringify(car);
          window.location.href = "detail.html?carData=" + encodeURIComponent(carDataStr);
        };

        carDiv.innerHTML = `
          <div class="car-img">
            <img loading="lazy" src="${imageUrl}" alt="Car Image">
          </div>
          <div class="car-text">
            <div class="car-title">${firstLine}</div>
            <div class="car-details">${secondAndRest}</div>
            ${countdownHtml}
          </div>
        `;
        carList.appendChild(carDiv);
      });
      
    }

    // 页面加载时，加载默认语言（但不自动隐藏覆盖层，这样每次都显示覆盖层）
    window.addEventListener("DOMContentLoaded", async () => {
      const chosenLang = localStorage.getItem("selectedLanguage") || "zh";
      document.getElementById("langSelect").value = chosenLang;
      const langData = await loadLanguage(chosenLang);
      applyLanguage(langData);
      onRentalTypeChange();
      // 如果想每次都显示覆盖层，可以不隐藏 langOverlay
      // 若只显示一次，请取消下面的注释：
      // document.getElementById("langOverlay").style.display = "none";
    });
  </script>
</body>
</html>